package com.tekj.cxqcb;

import android.Manifest;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.services.core.LatLonPoint;
import com.facebook.drawee.view.SimpleDraweeView;
import com.qw.soul.permission.SoulPermission;
import com.qw.soul.permission.bean.Permission;
import com.qw.soul.permission.bean.Permissions;
import com.qw.soul.permission.callbcak.CheckRequestPermissionsListener;
import com.squareup.picasso.Picasso;
import com.tekj.cxqcb.config.Urls;
import com.tekj.cxqcb.config.enums.EventBusMsgBean;
import com.tekj.cxqcb.operation.BusinessDao;
import com.tekj.cxqcb.operation.resultBean.AppLoginBean;
import com.tekj.cxqcb.operation.resultBean.VersionBean;
import com.tekj.cxqcb.view.Module.activity.ServiceOrder.OrderListActivity;
import com.tekj.cxqcb.view.Module.activity.StoreModule.AdministrationActivity;
import com.tekj.cxqcb.view.Module.activity.BalanceActivity;
import com.tekj.cxqcb.view.Module.activity.BuyingRecommendationActivity;
import com.tekj.cxqcb.view.Module.activity.CarConsultationActivity;
import com.tekj.cxqcb.view.Module.activity.Order.CarOrderListActivity;
import com.tekj.cxqcb.view.Module.activity.ExpandActivity;
import com.tekj.cxqcb.view.Module.activity.IdentityActivity;
import com.tekj.cxqcb.view.Module.activity.InvitationActivity;
import com.tekj.cxqcb.view.Module.activity.NewStoreManagementActivity;
import com.tekj.cxqcb.view.Module.activity.PublicStoresDetailsActivity;
import com.tekj.cxqcb.view.Module.activity.RelatedChannelsActivity;
import com.tekj.cxqcb.view.Module.activity.StoreModule.StoreManagementActivity;
import com.tekj.cxqcb.view.Module.activity.SystemActivity;
import com.tekj.cxqcb.view.Module.activity.TrafficManagementDetailsActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import common.base.InitApplication;
import common.base.MainApplication;
import common.base.activity.BaseActivity;
import common.base.operationHelper.Bean.BindingViewBean;
import common.conf.Service.helper.CityNameSet;
import common.plugins.tbs.WebCoreAction;
import common.tool.AppUpdateManager;
import common.widget.CircleTransform;
import es.dmoral.toasty.Toasty;

public class MainBActivity extends BaseActivity {

    @BindView(R.id.img_sdv_head)
    SimpleDraweeView imgSdvHead;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.tv_look)
    TextView tvLook;
    @BindView(R.id.tv_agent)
    TextView tvAgent;
    @BindView(R.id.ll_user_information)
    LinearLayout llUserInformation;
    @BindView(R.id.tv_tab1_num)
    TextView tvTab1Num;
    @BindView(R.id.tv_tab1)
    TextView tvTab1;
    @BindView(R.id.ll_zhye)
    LinearLayout llZhye;
    @BindView(R.id.tv_tab2_num)
    TextView tvTab2Num;
    @BindView(R.id.tv_tab2)
    TextView tvTab2;
    @BindView(R.id.ll_gcyx)
    LinearLayout llGcyx;
    @BindView(R.id.tv_tab3_num)
    TextView tvTab3Num;
    @BindView(R.id.tv_tab3)
    TextView tvTab3;
    @BindView(R.id.ll_mcdd)
    LinearLayout llMcdd;
    @BindView(R.id.tv_tab4_num)
    TextView tvTab4Num;
    @BindView(R.id.tv_tab4)
    TextView tvTab4;
    @BindView(R.id.ll_dpdd)
    LinearLayout llDpdd;
    @BindView(R.id.tv_mctj_num)
    TextView tvMctjNum;
    @BindView(R.id.ll_mctj)
    LinearLayout llMctj;
    @BindView(R.id.tv_mdgl_num)
    TextView tvMdglNum;
    @BindView(R.id.ll_mdgl)
    LinearLayout llMdgl;
    @BindView(R.id.tv_qdtz_num)
    TextView tvQdtzNum;
    @BindView(R.id.ll_qdtz)
    LinearLayout llQdtz;
    @BindView(R.id.tv_hylx_num)
    TextView tvHylxNum;
    @BindView(R.id.tv_istest)
    TextView tvIstest;
    @BindView(R.id.ll_lxgl)
    LinearLayout llLxgl;
    @BindView(R.id.ll_sz)
    LinearLayout llSz;

    public static AppLoginBean.DataBean User;
    private BusinessDao businessDao;
    private AppUpdateManager appUpdateManager;
    public static LatLonPoint latLonPoin;

    @Override
    public void init() {
        latLonPoin = new LatLonPoint(0, 0);
        EventBus.getDefault().register(this);
        InitApplication.getInstances().init(this);
        businessDao = new BusinessDao(this, this);
        User = (AppLoginBean.DataBean) getIntent().getBundleExtra("data").getSerializable("user");
        new CityNameSet(activity, tvIstest, 3);
        tvIstest.setText(isTest());
        businessDao.GetAppVersion();
        setViewData();
    }

    @Override
    public int setLayout() {
        return R.layout.activity_main_b;
    }

    @Override
    public void initLoadStart() {

    }

    @Override
    public void initLoadEnd() {

    }

    @Override
    public void initBindingView(Object mBean) {
        BindingViewBean bindingViewBean = (BindingViewBean) mBean;
        switch (bindingViewBean.getmEnumStatus()) {
            case 登陆2:
                AppLoginBean appLoginBean = (AppLoginBean) bindingViewBean.getBean();
                MainBActivity.User = appLoginBean.getData();
                setViewData();
                break;
            case 更新信息:
                VersionBean versionBean = (VersionBean) bindingViewBean.getBean();
                if (!versionBean.getCode().equals("0000000")) {
                    return;
                }
                appUpdateManager = new AppUpdateManager(activity, false, versionBean.getData());
                appUpdateManager.checkUpdate();
                break;
        }
    }

    @Override
    protected void onPause() {
        JPushInterface.onPause(this);
        super.onPause();
    }

    @Override
    protected void onResume() {
        JPushInterface.onResume(this);
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.ll_zhye, R.id.ll_gcyx, R.id.ll_mcdd,
            R.id.ll_dpdd, R.id.ll_mctj, R.id.ll_mdgl, R.id.ll_qdtz,
            R.id.ll_lxgl, R.id.ll_sz, R.id.ll_agent, R.id.ll_look,
            R.id.ll_ch})
    public void onViewClicked(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.ll_look:
                //TODO 身份
                intent = new Intent(activity, IdentityActivity.class);
                break;
            case R.id.ll_agent:
                //TODO 关联渠道
                intent = new Intent(activity, RelatedChannelsActivity.class);
                break;
            case R.id.ll_zhye:
                //TODO 账户余额
                intent = new Intent(activity, BalanceActivity.class);
//                PUB.WXShare(activity,"https://www.baidu.com","这是分享的标题","这是分享的内容");
                break;
            case R.id.ll_gcyx:
                //TODO 购车意向
                intent = new Intent(activity, CarConsultationActivity.class);

//                new WebCoreAction(activity, Urls.Domain_H5 + "/intention/"
//                        + User.getUserId()+"&token="+ MainApplication.UserToken);
                break;
            case R.id.ll_mcdd:
                //TODO 买车订单
//                new WebCoreAction(activity, Urls.Domain_H5 + "/business-order/"
//                        + User.getUserId()
////                        +"?token=" + MainApplication.UserToken
//                );
                intent = new Intent(activity, CarOrderListActivity.class);
                break;
            case R.id.ll_dpdd:
                //TODO 店铺订单
                if (User.getShopId().equals("")) {
                    Toasty.normal(activity, "您还没有申请店铺").show();
                    return;
                }
//                new WebCoreAction(activity, Urls.Domain_H5 + "/store-order/"
//                        + User.getUserId() + "?shopid=" + User.getShopId()
//                        + "&token=" + MainApplication.UserToken
//                );
                intent =new Intent(activity, OrderListActivity.class);
                break;
            case R.id.ll_mctj:
                //TODO 卖车推荐
                intent = new Intent(activity, BuyingRecommendationActivity.class);
                break;
//            case R.id.ll_mdgl1:
//                intent = new Intent(activity, AdministrationActivity.class);
//                break;
            case R.id.ll_mdgl:
                //TODO 门店管理
                SoulPermission.getInstance().checkAndRequestPermissions(
                        Permissions.build(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
                        // if you want do noting or no need all the callbacks you may use SimplePermissionsAdapter instead
                        new CheckRequestPermissionsListener() {
                            @Override
                            public void onAllPermissionOk(Permission[] allPermissions) {
                                if (User.getShopId().equals("")) {
                                    startActivity(new Intent(activity, AdministrationActivity.class));
                                } else
                                    activity.startActivity(new Intent(activity,
//                                            StoreManagementActivity.class
                                            NewStoreManagementActivity.class
                                    ));
                            }

                            @Override
                            public void onPermissionDenied(Permission[] refusedPermissions) {
                                Toasty.normal(activity, "缺少定位权限！").show();
                            }
                        });
                break;
            case R.id.ll_ch:
                //TODO 车行管理
                if (MainBActivity.User.getIsPublic() == 0) {
                    intent = new Intent(activity, PublicStoresDetailsActivity.class);
                } else if (MainBActivity.User.getIsPublic() == 1) {
                    intent = new Intent(activity, TrafficManagementDetailsActivity.class);
                } else {
                    Toasty.normal(activity, "车行暂未开通,请联系管理员").show();
                }
                break;
            case R.id.ll_qdtz:
                //TODO 渠道拓展
                intent = new Intent(activity, ExpandActivity.class);
                break;
            case R.id.ll_lxgl:
                //TODO 会员拉新
                intent = new Intent(activity, InvitationActivity.class);
                break;
            case R.id.ll_sz:
                //TODO 设置
                intent = new Intent(activity, SystemActivity.class);
                break;

        }

        if (intent != null) {
            startActivity(intent);
        }

    }

    private long mExitTime;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                //退出APP
                if ((System.currentTimeMillis() - mExitTime) > 2000) {
                    Toasty.normal(activity, "再按一次退出程序").show();
                    mExitTime = System.currentTimeMillis();
                } else {
                    finish();
                }
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    void setViewData() {

        tvUsername.setText(MainBActivity.User.getName());
        Picasso.get()
                .load(MainBActivity.User.getHead().equals("") ? "1" : MainBActivity.User.getHead())
                .transform(new CircleTransform())
                .into(imgSdvHead);
        tvTab1.setText(MainBActivity.User.getBalance() + "");
        tvTab2.setText(MainBActivity.User.getPurchaseAll() + "");
        tvTab3.setText(MainBActivity.User.getCarOrderNum() + "");
        tvTab4.setText(MainBActivity.User.getServiceOrderNum() + "");
        tvAgent.setText("代理区域：" + MainBActivity.User.getAddress());
        if (MainBActivity.User.getRole().equals("7")) {
//            4城市合伙人5运管中心7省分公司
            tvLook.setText("省分公司");
        } else if (MainBActivity.User.getRole().equals("5")) {
            tvLook.setText("运管中心");
        } else {
            tvLook.setText("城市合伙人");
        }

    }

    /**
     * 拼接uid到h5链接上
     *
     * @return
     */
    public static String getUserID() {
        if (User != null) {
            return "/" + User.getUserId();
        }
        return "";
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void Event(EventBusMsgBean e) {
        switch (e.getmEnumStatus()) {
            case 退出登陆刷新:
                finish();
                break;
            case 定位_经纬度:
                latLonPoin = (LatLonPoint) e.getObject();
                break;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        businessDao.selectUserById(User.getUserId());
    }

    String isTest() {
        if (Urls.Domain.equals("https://cars-cxqc.com")) {
            return "";
        }
        return "测试";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 101:
                    appUpdateManager.checkIsAndroidO();
                    break;
            }
        }
    }


}
